package com.gitee.huanminabc.utils_tools.config_refresh.listener;

import com.gitee.huanminabc.utils_tools.config_refresh.event.ConfigChangeEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ConfigurableWebEnvironment;

import java.util.Properties;

@Component
@Order(-1) //必须在所有配置修改监听器之前执行
public class ConfigEnvironmentChangeListener implements ApplicationListener<ConfigChangeEvent> {
    private final static String AUTO_REFRESH_PROPERTY_SOURCE = "AutoRefreshPropertySource";

    @Autowired(required = false) //如果没有找到就不注入,避免单元测试时候报错
    private ConfigurableWebEnvironment environment;
    @Override
    public void onApplicationEvent(ConfigChangeEvent event) {
        Properties properties = updatePropertySources(event);
        PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(AUTO_REFRESH_PROPERTY_SOURCE, properties);
        environment.getPropertySources().addFirst(propertiesPropertySource); //添加到第一个
    }

    //获取环境
    private Properties updatePropertySources(ConfigChangeEvent event) {
        Properties properties = new Properties();
        PropertySource<?> propertySource = environment.getPropertySources().get(AUTO_REFRESH_PROPERTY_SOURCE);//获取之前的配置(如果有的话
        if (propertySource == null) {//如果没有就创建一个
            properties.setProperty(event.getKey(), event.getValue().toString());
            return properties;
        }
        properties = (Properties) propertySource.getSource();
        properties.setProperty(event.getKey(), event.getValue().toString());

        //删除之前的配置
        environment.getPropertySources().remove(AUTO_REFRESH_PROPERTY_SOURCE);
        return properties;

    }

}
